<?php
/**
 * Order.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-19
 * Time: 19:14
 */

namespace App\Http\Controllers\Api\Business;


use App\Exceptions\RunException;
use App\Http\Controllers\Base;
use App\OSS\Client;
use App\Tables;
use App\Tool\RandomStr;

class Order extends Base
{
    public function createFast()
    {
        $customerId = (int) $this->request->post('selectCustomerId', 0);
        $customerName = '散客';
        $contactName = $this->request->post('contactsName') ?? '';
        $contactPhoneNumber = $this->request->post('contactsPhoneNumber') ?? '';
        $designPrice = (double) $this->request->post('designPrice', 0);
        $postPrintPrice = (double) $this->request->post('postPrintPrice', 0);
        $otherPrice = (double) $this->request->post('otherPrice', 0);
        $discountPrice = (double) $this->request->post('discountPrice', 0);
        $realPrice = (double) $this->request->post('realPrice', 0);
        $totalPrice = (double) $this->request->post('totalPrice', 0);
        $accountId = (int) $this->request->post('collectionAccount', 0);
        $remark = $this->request->post('remark');

        $business = (array) $this->request->post('business', []);

        if(empty($business)) {
            return $this->responseFail('请选择业务');
        }

        if($realPrice < 0) {
            return $this->responseFail('实际金额不能小于0');
        }

        if($accountId <= 0) {
            return $this->responseFail('请选择收款账户');
        }

        \DB::beginTransaction();
        try {
            $addTime = time();
            $orderNo = Tables\OrderMake::make();
            if($orderNo<=0){throw new RunException('保存失败(1)');}
            $customer = [
                'id' => $customerId,
                'name' => $customerName,
            ];
            if($customerId > 0) {
                $customer = Tables\Customer::find($customerId);
                if(empty($customer)) { throw new RunException('获取客户信息失败！'); }
            }

            $ok = Tables\Order::insert([
                'id' => $orderNo,
                'customer_id' => $customer['id'],
                'customer_name' => $customer['name'],
                'contacts_name' => $contactName,
                'contacts_phone_number' => $contactPhoneNumber,
                'deliver_method' => Tables\Order::Deliver_Method_Ok,
                'delivery_date' => date('Y-m-d'),
                'design_price' => $designPrice,
                'post_print_price' => $postPrintPrice,
                'other_price' => $otherPrice,
                'total_price' => $totalPrice,
                'discount_price' => $discountPrice,
                'real_price' => $realPrice,
                'paid_price' => $realPrice,
                'make_status' => Tables\Order::Make_Status_Ok,
                'delivery_status' => Tables\Order::Deliver_Method_Ok,
                'pay_status' => Tables\Order::Pay_status_Ok,
                'remark' => $remark,
                'add_time' => $addTime,
            ]);
            if(!$ok) { throw new RunException('保存失败(2)');}
            foreach ($business as $b) {
                $bid = $b['businessId'];
                $busInfo = Tables\Business::find($bid);
                if(empty($busInfo)) { throw new RunException('保存失败(2.5)');}

                $img = $b['checkImgB64'];
                $imgUrl = '';
                if(!empty($img)) {
                    $client = new Client();
                    $imgUrl = $client->upBase64Img($img);
                    if(empty($imgUrl))  {
                        throw new RunException('图片上传失败');
                    }
                }

                $odId = Tables\OrderDetail::insertGetId([
                    'oid' => $orderNo,
                    'bid' => $bid,
                    'b_name' => $busInfo['name'],
                    'count_type' => $busInfo['count_type'],
                    'unit' => $b['unit'],
                    'content' => $b['content'],
                    'width' => $b['width'],
                    'height' => $b['height'],
                    'number' => $b['number'],
                    'price'  => (double) $b['price'],
                    'total_price' => Tables\OrderDetail::getTotalPrice($busInfo['count_type'], $b['price'], $b['width'], $b['height'], $b['number']),
                    'check_img' => $imgUrl,
                    'make_status' => Tables\Order::Make_Status_Ok,
                    'complete_date' => date('Y-m-d'),
                    'add_time' => $addTime
                ]);
                if($odId <= 0) { throw new RunException('保存失败(5)');}

                $insertData = [];
                foreach($b['consumable'] as $ceId) {
                    $consumable = Tables\Consumable::find($ceId);
                    if(!empty($consumable)) {
                        $insertData[] = [
                            'oid' => $orderNo,
                            'od_id' => $odId,
                            'bid' => $bid,
                            'cid' => $consumable['id'],
                            'c_name' => $consumable['name'],
                            'add_time' => $addTime
                        ];
                    }
                }
                $ok = (bool) Tables\OrderConsumable::insert($insertData);
                if(!$ok) { throw new RunException('保存失败(3)'); }

                $insertData = [];
                foreach ($b['postPrint'] as $ppId) {
                    $postPrint = Tables\PostPrint::find($ppId);
                    if(!empty($postPrint)) {
                        $insertData[] = [
                            'oid' => $orderNo,
                            'od_id' => $odId,
                            'bid' => $bid,
                            'pid' => $ppId,
                            'p_name' => $postPrint['name'],
                            'add_time' => $addTime
                        ];
                    }
                }
                $ok = (bool) Tables\OrderPostPrint::insert($insertData);
                if(!$ok) { throw new RunException('保存失败(4)');}

            } // end foreach

            $account = Tables\Account::find($accountId);
            if(empty($account)) {
                throw new RunException('保存失败(6)');
            }
            $ok = (bool) Tables\OrderPay::insert([
                'oid' => $orderNo,
                'aid' => $account['id'],
                'a_name' => $account['name'],
                'money' => $realPrice,
                'add_time' => $addTime
            ]);
            if(!$ok) {
                throw new RunException('保存失败(7)');
            }
            $ok = (bool) Tables\CashFlow::insert([
                'change' => $realPrice,
                'desc'   => "{$orderNo}订单支付",
                'type'   => Tables\CashFlow::TYPE_Income_Order,
                'add_time' => $addTime
            ]);
            if(!$ok) {
                throw new RunException('保存失败(7.5)');
            }

            $ok = (bool) Tables\OrderEvent::insert([
                'type' => Tables\OrderEvent::TYPE_Normal,
                'desc' => '创建了快速订单',
                'oid'  => $orderNo,
                'add_time' => $addTime
            ]);
            if(!$ok) {
                throw new RunException('保存失败(8)');
            }

            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e->getMessage());
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function create()
    {
        $customerId = (int) $this->request->post('selectCustomerId', 0);
        $customerName = '散客';
        $contactId = (int) $this->request->post('selectCustomerContactsId', 0);
        $contactName = $this->request->post('contactsName') ?? '';
        $contactPhoneNumber = $this->request->post('contactsPhoneNumber') ?? '';
        $deliverMethod = (int) $this->request->post('selectDeliverMethod', 0);
        $deliverAddress = $this->request->post('deliverAddress') ?? '';
        $deliveryDate =  $this->request->post('deliveryDate', 0);
        $isNeedInstall = (bool) $this->request->post('isNeedInstall', false);
        $isNeedInvoice = (bool) $this->request->post('isNeedInvoice', false);
        $invoiceNumber = $this->request->post('invoiceNumber');
        $designPrice = (double) $this->request->post('designPrice', 0);
        $postPrintPrice = (double) $this->request->post('postPrintPrice', 0);
        $installPrice = (double) $this->request->post('installPrice', 0);
        $taxPrice = (double) $this->request->post('taxPrice', 0);
        $otherPrice = (double) $this->request->post('otherPrice', 0);
        $totalPrice = (double) $this->request->post('totalPrice', 0);
        $discountPrice = (double) $this->request->post('discountPrice', 0);
        $realPrice = (double) $this->request->post('realPrice', 0);
        $paidPrice = (double) $this->request->post('paidPrice', 0);
        $accountId = (int) $this->request->post('collectionAccount', 0);
        $remark = $this->request->post('remark');

        $business = (array) $this->request->post('business', []);

        if($deliverMethod <= 0) {
            return $this->responseFail('请选择送货方式');
        }
        if($customerId == 0 and $deliverMethod != 1) {
            return $this->responseFail('散客只能自取，请增加客户或选择自取！');
        }

        if(empty($business)) {
            return $this->responseFail('请选择业务');
        }

        if($realPrice < 0) {
            return $this->responseFail('实际金额不能小于0');
        }

        if($paidPrice > 0 && $accountId <= 0) {
            return $this->responseFail('请选择收款账户');
        }

        \DB::beginTransaction();
        try{
            $addTime = time();
            $orderNo = Tables\OrderMake::make();
            if($orderNo<=0){throw new RunException('保存失败(1)');}
            $customer = [
                'id' => $customerId,
                'name' => $customerName,
            ];
            if($customerId > 0) {
                $customer = Tables\Customer::find($customerId);
                if(empty($customer)) { throw new RunException('获取客户信息失败！'); }
            }
            $ok = Tables\Order::insert([
                'id' => $orderNo,
                'customer_id' => $customer['id'],
                'customer_name' => $customer['name'],
                'contacts_id' => $contactId,
                'contacts_name' => $contactName,
                'contacts_phone_number' => $contactPhoneNumber,
                'deliver_method' => $deliverMethod,
                'deliver_address' => $deliverAddress,
                'delivery_date' => date('Y-m-d', strtotime($deliveryDate)),
                'need_install' => $isNeedInstall ? 1 : 0,
                'need_invoice' => $isNeedInvoice ? 1 : 0,
                'invoice_number' => $isNeedInvoice ? $invoiceNumber : '',
                'design_price' => $designPrice,
                'post_print_price' => $postPrintPrice,
                'install_price' => $installPrice,
                'tax_price' => $taxPrice,
                'other_price' => $otherPrice,
                'total_price' => $totalPrice,
                'discount_price' => $discountPrice,
                'real_price' => $realPrice,
                'paid_price' => $paidPrice,
                'delivery_status' => $deliverMethod == Tables\Order::Deliver_Method_Ok ? Tables\Order::Delivery_Status_Ok : Tables\Order::Delivery_Status_No,
                'pay_status' => $paidPrice >= $realPrice ? Tables\Order::Pay_status_Ok : Tables\Order::Pay_status_No,
                'remark' => $remark,
                'add_time' => $addTime,
            ]);
            if(!$ok) { throw new RunException('保存失败(2)');}

            $hash = RandomStr::make(6);
            $find = Tables\CustomerHash::query()->where('hash', $hash)->first();
            if(!empty($find)) {
                $ok = (bool) $find->delete();
                if(!$ok) { throw new RunException('保存失败(2.1)'); }
            }
            $ok = (bool) Tables\CustomerHash::insert([
                'hash' => $hash, 'cid' => $customer['id'], 'exp' => $addTime + 1800, 'add_time' => $addTime
            ]);
            if(!$ok) { throw new RunException('保存失败(2.2)'); }

            foreach ($business as $b) {
                $bid = $b['businessId'];
                $busInfo = Tables\Business::find($bid);
                if(empty($busInfo)) { throw new RunException('保存失败(2.5)');}

                $img = $b['checkImgB64'];
                $imgUrl = '';
                if(!empty($img)) {
                    $client = new Client();
                    $imgUrl = $client->upBase64Img($img);
                    $imgUrl = Tables\OrderDetail::getRightImg($imgUrl);
                    if(empty($imgUrl))  {
                        throw new RunException('图片上传失败');
                    }
                }

                $outsourceName = '';
                if(!empty($b['outsourceId'])) {
                    $outsource = Tables\Outsource::find($b['outsourceId']);
                    $outsourceName = $outsource['name'];
                }

                $odId = Tables\OrderDetail::insertGetId([
                    'oid' => $orderNo,
                    'bid' => $bid,
                    'b_name' => $busInfo['name'],
                    'count_type' => $busInfo['count_type'],
                    'unit' => $b['unit'],
                    'content' => $b['content'],
                    'width' => $b['width'],
                    'height' => $b['height'],
                    'number' => $b['number'],
                    'price'  => (double) $b['price'],
                    'total_price' => Tables\OrderDetail::getTotalPrice($busInfo['count_type'], $b['price'], $b['width'], $b['height'], $b['number']),
                    'check_img' => $imgUrl,
                    'outsource_id' => (int) $b['outsourceId'],
                    'outsource_name' => $outsourceName,
                    'make_status' => Tables\Order::Make_Status_No,
                    'complete_date' => implode('-', $b['date']),
                    'add_time' => $addTime
                ]);
                if($odId <= 0) { throw new RunException('保存失败(5)');}

                $insertData = [];
                foreach($b['consumable'] as $ceId) {
                    $consumable = Tables\Consumable::find($ceId);
                    if(!empty($consumable)) {
                        $insertData[] = [
                            'oid' => $orderNo,
                            'od_id' => $odId,
                            'bid' => $bid,
                            'cid' => $consumable['id'],
                            'c_name' => $consumable['name'],
                            'add_time' => $addTime
                        ];
                    }
                }
                $ok = (bool) Tables\OrderConsumable::insert($insertData);
                if(!$ok) { throw new RunException('保存失败(3)'); }

                $insertData = [];
                foreach ($b['postPrint'] as $ppId) {
                    $postPrint = Tables\PostPrint::find($ppId);
                    if(!empty($postPrint)) {
                        $insertData[] = [
                            'oid' => $orderNo,
                            'od_id' => $odId,
                            'bid' => $bid,
                            'pid' => $ppId,
                            'p_name' => $postPrint['name'],
                            'add_time' => $addTime
                        ];
                    }
                }
                $ok = (bool) Tables\OrderPostPrint::insert($insertData);
                if(!$ok) { throw new RunException('保存失败(4)');}

            } // end foreach

            if($paidPrice > 0) {
                $account = Tables\Account::find($accountId);
                if(empty($account)) {
                    throw new RunException('保存失败(6)');
                }
                $ok = (bool) Tables\OrderPay::insert([
                    'oid' => $orderNo,
                    'aid' => $account['id'],
                    'a_name' => $account['name'],
                    'money' => $paidPrice,
                    'add_time' => $addTime
                ]);
                if(!$ok) {
                    throw new RunException('保存失败(7)');
                }
                $ok = (bool) Tables\CashFlow::insert([
                    'change' => $paidPrice,
                    'desc'   => "{$orderNo}订单支付",
                    'type'   => Tables\CashFlow::TYPE_Income_Order,
                    'add_time' => $addTime
                ]);
                if(!$ok) {
                    throw new RunException('保存失败(7.5)');
                }
            }

            $ok = (bool) Tables\OrderEvent::insert([
                'type' => Tables\OrderEvent::TYPE_Normal,
                'desc' => '创建了订单',
                'oid'  => $orderNo,
                'add_time' => $addTime
            ]);
            if(!$ok) {
                throw new RunException('保存失败(8)');
            }

            \DB::commit();
        }catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e->getMessage());
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess([
            'id' => $orderNo,
            'no' => $orderNo,
            'hash' => $hash
        ]);
    }

    public function getList()
    {
        $firstDate = $this->request->get('firstDate');
        $lastDate = $this->request->get('lastDate');
        $customerName = $this->request->get('customerName');
        $businessName = $this->request->get('businessName');
        $outsourceName = $this->request->get('outsourceName');
        $orderNo = $this->request->get('orderNo');
        $orderStatus = (int) $this->request->get('orderStatus', 0);
        $deliverStatus = (int) $this->request->get('deliverStatus', 0);
        $payStatus = (int) $this->request->get('payStatus', 0);
        $isNeedInstall = (int) $this->request->get('isNeedInstall', -1);
        $isNeedInvoice = (int) $this->request->get('isNeedInvoice', -1);
        $page = (int) $this->request->get('page', 1);
        $pageSize = (int) $this->request->get('pageSize', 30);
        $overTime = (bool) $this->request->get('overtime', 0);
        $noPay = (bool) $this->request->get('noPay', 0);
        $dumped   = (int) $this->request->get('dumped', 0);

        $table = Tables\Order::query();
        if($overTime) {
            $today = date('Y-m-d');
            $table->where('delivery_date', '<=', "DATE('{$today}')");
            $table->where('delivery_status', '!=', Tables\Order::Delivery_Status_Ok);
            $table->where('dumped', Tables\Order::No_Dumped);
        } else if ($noPay) {
            $table->where('pay_status', Tables\Order::Pay_status_No);
            $table->where('dumped', Tables\Order::No_Dumped);
        }else {
            $customerName  = preg_replace('/\(.*\)/', '', $customerName);
            $cid           = (int) $this->request->get('cid', 0);
            $businessName  = preg_replace('/\(.*\)/', '', $businessName);
            $bid           = (int) $this->request->get('bid', 0);
            $outsourceName = preg_replace('/\(.*\)/', '', $outsourceName);
            $oid           = (int) $this->request->get('oid', 0);
            if($cid > 0) {
                $table->where('customer_id', $cid);
            } else if(!empty($customerName)) {
                $table->where('customer_name', $customerName);
            }

            if($bid > 0 or !empty($businessName) or $oid > 0 or !empty($outsourceName)) {
                $table->leftJoin('order_detail','order_detail.oid', '=', 'order.id');
                $table->select('order.*');
            }

            if($bid > 0) {
                $table->where('order_detail.bid', $bid);
            } else if(!empty($businessName)) {
                $table->where('order_detail.b_name', $businessName);
            }

            if($oid > 0) {
                $table->where('order_detail.outsource_id', $oid);
            } else  if(!empty($outsourceName)){
                $table->where('order_detail.outsource_name', $outsourceName);
            }

            if(empty($firstDate) || empty($lastDate)) {
                $firstDate = strtotime(date('Ymd'));
                $lastDate  = $firstDate + 86400;
            } else {
                $firstDate = strtotime($firstDate);
                $lastDate  = strtotime($lastDate) + 86400;
            }
            if($this->request->has('firstDate') and $this->request->has('lastDate')) {
                $table->whereBetween('order.add_time', [$firstDate, $lastDate]);
            }

            if(empty($orderNo) and $cid <= 0) {
                $table->whereBetween('order.add_time', [$firstDate, $lastDate]);
            }

            if(!empty($orderNo)) {
                $table->where('id', $orderNo);
            }

            if($orderStatus > 0) {
                $table->where('make_status', $orderStatus);
            }

            if($deliverStatus > 0) {
                $table->where('delivery_status', $deliverStatus);
            }

            if($payStatus > 0) {
                $table->where('pay_status', $payStatus);
            }

            if($isNeedInstall > 0) {
                $table->where('need_install', 1);
            }

            if($isNeedInvoice > 0) {
                $table->where('need_invoice', 1);
            }
            if($this->request->has('dumped')) {
                $table->where('dumped', $dumped);
            }
        }

        $table->offset(($page - 1) * $pageSize)->limit($pageSize);
        $orderList = $table->orderBy('order.id', 'desc')->get();
        $rList = [];
        foreach($orderList as $order) {
            $bList = [];
            foreach($order->details as $detail) {
                $ccList = $detail->consumables()->where('bid', $detail['bid'])->get();
                $ppList = $detail->postPrints()->where('bid', $detail['bid'])->get();
                $postPrint = $consumable = [];
                foreach($ccList as $v) {
                    $consumable[] = $v['c_name'];
                }
                foreach ($ppList as $v) {
                    $postPrint[] = $v['p_name'];
                }
                $bList[] = [
                    'businessName' => $detail['b_name'],
                    'content' => $detail['content'],
                    'consumable' => $consumable,
                    'postPrint' => $postPrint,
                    'unit' => $detail['unit'],
                    'area' => Tables\OrderDetail::getArea($detail['count_type'], $detail['width'], $detail['height']),
                    'width' => $detail['width'],
                    'height' => $detail['height'],
                    'number' => $detail['number'],
                    'price' => $detail['price'],
                    'totalPrice' => $detail['total_price'],
                    'outsourceName' => $detail['outsource_name'],
                    'completeDate' => $detail['complete_date'],
                    'img' => Tables\OrderDetail::getRightImg($detail['check_img']),
                    'countType' => Tables\Business::query()->where('id', $detail['bid'])->value('count_type'),
                    'makeStatus' => $detail['make_status']
                ];
            }

            $rList[] = [
                'no' => $order['id'],
                'customerName' => $order['customer_name'],
                'contactsName' => $order['contacts_name'],
                'contactsPhoneNumber' => $order['contacts_phone_number'],
                'createTime' => date('Y-m-d H:i:s',$order['add_time']),
                'deliverMethod' => $order['deliver_method'],
                'deliverAddress' => $order['deliver_address'],
                'isNeedInstall' => $order['need_install'],
                'deliveryDate' => $order['delivery_date'],
                'isNeedInvoice' => $order['need_invoice'],
                'invoiceNumber' => $order['invoice_number'],
                'designPrice' => $order['design_price'],
                'postPrintPrice' => $order['post_print_price'],
                'installPrice' => $order['install_price'],
                'taxPrice' => $order['tax_price'],
                'otherPrice' => $order['other_price'],
                'totalPrice' => $order['total_price'],
                'discountPrice' => $order['discount_price'],
                'realPrice' => $order['real_price'],
                'paidPrice' => $order['paid_price'],
                'collectionAccount' => '',
                'makeStatus' => $order['make_status'],
                'deliveryStatus' => $order['delivery_status'],
                'payStatus' => $order['pay_status'],
                'dumped' => $order['dumped'],
                'remark' => $order['remark'],
                'business' => $bList

            ];
        } // end foreach

        $complete = $make = $delivery = $express = $logistics = $install = $invoice = $noPay = $partPay = $paid = 0;
        $debt = $deposit = $totalPrice = $discountPrice = $paidPrice = 0;
        $fd = $ld = 0;
        foreach($rList  as $v) {
            if($v['dumped'] == Tables\Order::Dumped) { continue; }
            if(
                $v['makeStatus'] == Tables\Order::Make_Status_Ok and
                $v['deliveryStatus'] == Tables\Order::Delivery_Status_Ok and
                $v['payStatus'] == Tables\Order::Pay_status_Ok
            ) { $complete ++ ;}
            if($v['makeStatus'] == Tables\Order::Make_Status_No) { $make ++ ;}
            if($v['deliverMethod'] == 2 and $v['deliveryStatus'] == Tables\Order::Delivery_Status_No) { $delivery ++;}
            if($v['deliverMethod'] == 3 and $v['deliveryStatus'] == Tables\Order::Delivery_Status_No) { $express ++;}
            if($v['deliverMethod'] == 4 and $v['deliveryStatus'] == Tables\Order::Delivery_Status_No) { $logistics ++;}
            if($v['isNeedInstall']) { $install ++; }
            if($v['isNeedInvoice']) { $invoice ++; }
            if($v['paidPrice'] <=0 ) { $noPay++;}
            if($v['paidPrice'] < $v['realPrice']) { $debt += $v['realPrice'] - $v['paidPrice']; $partPay ++;}
            if($v['payStatus'] == Tables\Order::Pay_status_Ok) { $paid ++;}
            $deposit += $v['paidPrice'];
            $totalPrice += $v['realPrice'];
            $discountPrice += $v['discountPrice'];
            $paidPrice += $v['paidPrice'];
            if(strtotime($v['createTime']) > $ld and $ld > 0) {
                $ld = strtotime($v['createTime']);
            } else if($ld == 0) {
                $ld =strtotime($v['createTime']);
            }

            if(strtotime($v['createTime']) < $fd and $fd > 0) {
                $fd = strtotime($v['createTime']);
            } else if ($fd == 0) {
                $fd = strtotime($v['createTime']);
            }
        }

        $header = [
            'total' => count($rList),
            'complete' => $complete,
            'make' => $make,
            'delivery' => $delivery,
            'express' => $express,
            'logistics' => $logistics,
            'install' => $install,
            'invoice' => $invoice,
            'noPay' => $noPay,
            'partPay' => $partPay,
            'paid' => $paid,
            'debt' => $debt,
            'deposit' => $deposit,
            'paidPrice' => $paidPrice,
            'totalPrice' => $totalPrice,
            'discountPrice' => $discountPrice,
            'lastDate' => date('Y-m-d', $ld),
            'firstDate' => date('Y-m-d', $fd)
        ];


        return $this->responseSuccess(['header' => $header, 'list' => $rList]);
    }

    public function get()
    {
        $no = $this->request->get('no', '');
        if(empty($no)) {
            return $this->responseSuccess();
        }
        $order = Tables\Order::find($no);
        if(empty($order)) {
            return $this->responseSuccess();
        }
        $bList = $proceeds = $events = [];

        foreach($order->details as $b) {
            $consumable = $postPrint = [];
            foreach($b->consumables as $v) {
                $consumable[] = [
                    'id' => $v['cid'],
                    'name' => $v['c_name']
                ];
            }
            foreach ($b->postPrints as $v) {
                $postPrint[] = [
                    'id' => $v['pid'],
                    'name' => $v['p_name']
                ];
            }
            $bList[] = [
                'id' => $b['id'],
                'businessId' => $b['bid'],
                'businessName' => $b['b_name'],
                'consumable' => $consumable,
                'postPrint' => $postPrint,
                'unit' => $b['unit'],
                'content' => $b['content'],
                'width' => $b['width'],
                'height' => $b['height'],
                'number' => $b['number'],
                'price' => $b['price'],
                'totalPrice' => $b['total_price'],
                'outsourceName' => $b['outsource_name'],
                'outsourceId' => $b['outsource_id'],
                'completeDate' => $b['complete_date'],
                'checkImg' => Tables\OrderDetail::getRightImg($b['check_img']),
            ];
        }

        foreach($order->pays as $v) {
            $proceeds[] = [
                'id' => $v['id'],
                'account' => $v['a_name'],
                'accountId' => $v['aid'],
                'money' => $v['money'],
                'time' => date('Y-m-d H:i:s', $v['add_time'])
            ];
        }

        foreach($order->events as $v) {
            $events[] = [
                'id' => $v['id'],
                'eventType' => $v['type'],
                'desc' => $v['desc'],
                'time' => date('Y-m-d H:i:s', $v['add_time'])
            ];
        }

        $r = [
            'id'=> $order['id'],
            'no'=> $order['id'],
            'customer'=> ['id' => $order['customer_id'], 'name' => $order['customer_name']],
            'contacts'=> ['name' => $order['contacts_name'], 'phoneNumber' => $order['contacts_phone_number']],
            'deliverMethod'=> $order['deliver_method'],
            'deliverAddress'=> $order['deliver_address'],
            'deliveryDate'=> $order['delivery_date'],
            'addTime'=> date('Y-m-d H:i:s', $order['add_time']),
            'isNeedInstall'=> $order['need_install'],
            'isNeedInvoice'=> $order['need_invoice'],
            'invoiceNumber'=> $order['invoice_number'],
            'designPrice'=> $order['design_price'],
            'postPrintPrice'=> $order['post_print_price'],
            'installPrice'=> $order['install_price'],
            'taxPrice'=> $order['tax_price'],
            'otherPrice'=> $order['other_price'],
            'totalPrice'=> $order['total_price'],
            'discountPrice'=> $order['discount_price'],
            'realPrice'=> $order['real_price'],
            'paidPrice'=> $order['paid_price'],
            'makeStatus'=> $order['make_status'],
            'deliveryStatus'=> $order['delivery_status'],
            'payStatus'=> $order['pay_status'],
            'remark'=> $order['remark'],
            'dumped'=> $order['dumped'],
            'business' => $bList,
            'proceeds' => $proceeds,
            'events' => $events,
        ];



        return $this->responseSuccess($r);
    }

    public function payMoney()
    {
        $no = $this->request->post('no');
        $money = (double) $this->request->post('money', 0);
        $payId = (int) $this->request->post('payId', 0);
        if(empty($no)) {
            return $this->responseFail('无信息！');
        }
        if($money <= 0) {
            return $this->responseFail('请填写金额');
        }
        if($payId <= 0) {
            return $this->responseFail('请选择支付方式');
        }

        \DB::beginTransaction();
        try {
            $addTime = time();
            $order = Tables\Order::find($no);
            if(empty($order)) { throw new RunException('未找到订单信息'); }
            $account = Tables\Account::find($payId);
            if(empty($account)) { throw new RunException('没有找到支付方式'); }
            if($order['pay_status'] == Tables\Order::Pay_status_Ok) {
                throw new RunException('该订单已经支付完成了！');
            }
            $paidPrice = (double) $order['paid_price'] + $money;
            $order['paid_price'] = $paidPrice;
            if($paidPrice >= $order['real_price']) {
                $order['pay_status'] = Tables\Order::Pay_status_Ok;
            }
            $ok = (bool) $order->save();
            if(!$ok) { throw new RunException('操作失败(1)'); }
            $ok = (bool) Tables\OrderPay::insert([
                'oid' => $order['id'],
                'aid' => $account['id'],
                'a_name' => $account['name'],
                'money' => $money,
                'add_time' => $addTime
            ]);
            if(!$ok) { throw new RunException('操作失败(2)'); }
            $ok = (bool) Tables\OrderEvent::insert([
                'type' => Tables\OrderEvent::TYPE_Change,
                'desc' => '支付了'.$money.'元',
                'oid'  => $order['id'],
                'add_time' => $addTime
            ]);
            if(!$ok) { throw new RunException('操作失败(3)'); }
            if($order['pay_status'] == Tables\Order::Pay_status_Ok) {
                $ok = (bool) Tables\OrderEvent::insert([
                    'type' => Tables\OrderEvent::TYPE_Normal,
                    'desc' => '订单支付完成',
                    'oid'  => $order['id'],
                    'add_time' => $addTime
                ]);
                if(!$ok) { throw new RunException('操作失败(4)'); }
            }
            $ok = (bool) Tables\CashFlow::insert([
                'change' => $money,
                'desc'   => "{$no}订单支付",
                'type'   => Tables\CashFlow::TYPE_Income_Order,
                'add_time' => $addTime
            ]);
            if(!$ok) { throw new RunException('操作失败(5)'); }

            \DB::commit();
        } catch(RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function dump()
    {
        $no = $this->request->post('orderNo');
        if(empty($no)) {
            return $this->responseFail('没有信息');
        }

        $order = Tables\Order::find($no);
        if(empty($order)) {
            return $this->responseFail('没有订单信息！');
        }
        if($order['pay_status'] == Tables\Order::Pay_status_Ok) {
            return $this->responseFail('订单支付已完成无法作废!');
        }
        if($order['delivery_status'] == Tables\Order::Delivery_Status_Ok) {
            return $this->responseFail('订单送货已完成无法作废!');
        }
        \DB::beginTransaction();
        $order['dumped'] = Tables\Order::Dumped;
        try {
            $ok = (bool) $order->save();
            if(!$ok) { throw new RunException('作废失败！(1)');}
            $ok = (bool) Tables\OrderEvent::insert([
                'type' => Tables\OrderEvent::TYPE_Danger,
                'desc' => '作废了订单',
                'oid'  => $order['id'],
                'add_time' => time()
            ]);
            if(!$ok) { throw new RunException('作废失败！(2)');}
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function changeStatus()
    {
        $no = $this->request->post('orderNo');
        $makeStatus = (int) $this->request->post('makeStatus', 0);
        $deliveryStatus = (int) $this->request->post('deliveryStatus', 0);
        if(empty($no)) {
            return $this->responseFail('无信息');
        }
        if($makeStatus <= 0 and $deliveryStatus <= 0) {
            return $this->responseFail('无修改信息');
        }
        $order = Tables\Order::find($no);
        if(empty($order)) {
            return $this->responseFail('查询不到信息');
        }
        if(
            $makeStatus > 0 and $order['make_status'] == $makeStatus and
            $deliveryStatus > 0 and $order['delivery_status'] == $deliveryStatus) {
            return $this->responseFail('无修改');
        }

        if(!in_array($makeStatus, Tables\Order::Make_Status_Arr)) {
            return $this->responseFail('修改状态错误!');
        }

        if(!in_array($deliveryStatus, Tables\Order::Delivery_Status_Arr)) {
            return $this->responseFail('修改状态错误!');
        }


        \DB::beginTransaction();
        try {
            $addTime = time();
            if($makeStatus > 0 and $makeStatus != $order['make_status']) {
                $ok = (bool) Tables\OrderEvent::insert([
                    'type' => Tables\OrderEvent::TYPE_Change,
                    'desc' => '修改订单制作状态为'.Tables\Order::Make_Status_Cn[$makeStatus],
                    'oid'  => $order['id'],
                    'add_time' => $addTime
                ]);
                if(!$ok) { throw new RunException('修改失败！(1)');}
                foreach($order->details as $od){ //关联明细表也要修改
                    $od['make_status'] = $makeStatus;
                    if(!(bool) $od->save()) {
                        throw new RunException('修改失败！(2)');
                    }
                }
            }
            if($deliveryStatus > 0 and $deliveryStatus != $order['delivery_status']) {
                $ok = (bool) Tables\OrderEvent::insert([
                    'type' => Tables\OrderEvent::TYPE_Change,
                    'desc' => '修改订单送货状态为'.Tables\Order::Delivery_Status_Cn[$deliveryStatus],
                    'oid'  => $order['id'],
                    'add_time' => $addTime
                ]);
                if(!$ok) { throw new RunException('修改失败！(3)');}
            }
            if($makeStatus > 0) { $order['make_status'] = $makeStatus; }
            if($deliveryStatus > 0) { $order['delivery_status'] = $deliveryStatus; }
            $ok = (bool) $order->save();
            if(!$ok) { throw new RunException('修改失败！(4)');}

            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function SetMakeComplete()
    {
        $idList = (array) $this->request->post('no', []);
        if(empty($idList)) {
            return $this->responseFail('无信息');
        }
        $idList = array_filter($idList);
        $orderList  = Tables\Order::whereIn('id', $idList)->get();
        if($orderList->isEmpty()) {
            return $this->responseFail('没有找到订单信息');
        }

        \DB::beginTransaction();
        try {
            $addTime = time();
            foreach($orderList as $o) {
                if($o['make_status'] != Tables\Order::Make_Status_Ing) {
                    throw new RunException('只有制作中的订单才能执行完成操作!');
                }
                $o['make_status'] = Tables\Order::Make_Status_Ok;
                if(!(bool) $o->save()) {
                    throw new RunException('操作失败(1)');
                }
                foreach($o->details as $od) { // 操作明细
                    $od['make_status'] = Tables\Order::Make_Status_Ok;
                    if(!(bool) $od->save()) {
                        throw new RunException('操作失败(1)');
                    }
                }
                $ok = (bool) Tables\OrderEvent::insert([
                    'type' => Tables\OrderEvent::TYPE_Change,
                    'desc' => '修改订单制作状态为'.Tables\Order::Make_Status_Cn[Tables\Order::Make_Status_Ok],
                    'oid'  => $o['id'],
                    'add_time' => $addTime
                ]);
                if(!$ok) { throw new RunException('操作失败！(2)');}
            }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function SetDelivery()
    {
        $idList = (array) $this->request->post('no', []);
        if(empty($idList)) {
            return $this->responseFail('无信息');
        }

        $idList = array_filter($idList);
        $orderList  = Tables\Order::whereIn('id', $idList)->get();
        if($orderList->isEmpty()) {
            return $this->responseFail('没有找到订单信息');
        }

        \DB::beginTransaction();
        try {
            $addTime = time();
            foreach($orderList as $o) {
                if($o['delivery_status'] != Tables\Order::Delivery_Status_Ing) {
                    throw new RunException('只有送货中的订单才能执行完成操作!');
                }
                $o['delivery_status'] = Tables\Order::Delivery_Status_Ok;
                if(!(bool) $o->save()) {
                    throw new RunException('操作失败(1)');
                }
                $ok = (bool) Tables\OrderEvent::insert([
                    'type' => Tables\OrderEvent::TYPE_Change,
                    'desc' => '修改订单送货状态为'.Tables\Order::Delivery_Status_Cn[Tables\Order::Delivery_Status_Ok],
                    'oid'  => $o['id'],
                    'add_time' => $addTime
                ]);
                if(!$ok) { throw new RunException('操作失败！(2)');}
            }
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }


    public function update()
    {
        $no = $this->request->post('id');
        $contacts = (array) $this->request->post('contacts');
        $deliverMethod = (int) $this->request->post('deliverMethod');
        $deliverAddress = $this->request->post('deliverAddress');
        $deliveryDate = $this->request->post('deliveryDate');
        $isNeedInstall = (bool) $this->request->post('isNeedInstall');
        $isNeedInvoice = (bool) $this->request->post('isNeedInvoice');
        $invoiceNumber = $this->request->post('invoiceNumber');
        $designPrice = (double) $this->request->post('designPrice');
        $postPrintPrice = (double) $this->request->post('postPrintPrice');
        $installPrice = (double) $this->request->post('installPrice');
        $taxPrice = (double) $this->request->post('taxPrice');
        $otherPrice = (double) $this->request->post('otherPrice');
        $totalPrice = (double) $this->request->post('totalPrice');
        $discountPrice = (double) $this->request->post('discountPrice');
        $realPrice =  (double)$this->request->post('realPrice');
        $remark = $this->request->post('remark');
        $business = (array) $this->request->post('business', []);

        if(empty($no)) {
            return $this->responseFail('无信息');
        }
        $order = Tables\Order::find($no);
        if(empty($order)) {
            return $this->responseFail('未找到订单信息');
        }

        \DB::beginTransaction();

        try {
            $addTime = time();
            $eventDesc = [];
            if($order['contacts_name'] != $contacts['name']) {
                $order['contacts_name'] = $contacts['name'];
                $eventDesc[] = '修改了联系人名称为'.$contacts['name'];
            }
            if($order['contacts_phone_number'] != $contacts['phoneNumber']) {
                $order['contacts_phone_number'] = $contacts['phoneNumber'];
                $eventDesc[] = '修改了联系人电话为'.$contacts['phoneNumber'];
            }
            if($order['deliver_method'] != $deliverMethod) {
                $order['deliver_method'] = $deliverMethod;
                $eventDesc[] = '修改了送货方式为'. Tables\Order::Deliver_Method_Cn[$deliverMethod];
                if($deliverMethod == Tables\Order::Deliver_Method_Ok) {
                    $order['delivery_status'] = Tables\Order::Delivery_Status_Ok;
                }
            }
            if($order['deliver_address'] != $deliverAddress) {
                $order['deliver_address'] = $deliverAddress;
                $eventDesc[] = '修改了送货地址为'.$deliverAddress;
            }
            if($order['delivery_date'] != $deliveryDate) {
                $order['delivery_date'] = $deliveryDate;
                $eventDesc[] = '修改了送货日期为'.$deliveryDate;
            }
            if($order['need_install'] != (int) $isNeedInstall) {
                $order['need_install'] = $isNeedInstall ? 1 : 0;
                $eventDesc[] = '修改了订单安装需要为'. ($isNeedInstall? '需要安装' : '不需要安装');
            }
            if($order['need_invoice'] != (int) $isNeedInvoice) {
                $order['need_invoice'] = $isNeedInvoice ? 1 : 0;
                $eventDesc[] = '修改了订单发票需要为'. ($isNeedInvoice? '需要开票' : '不需要开票');
            }
            if($order['invoice_number'] != $invoiceNumber) {
                $order['invoice_number'] = $invoiceNumber;
                $eventDesc[] = '修改了发票号码为'.$invoiceNumber;
            }
            if($order['design_price'] != $designPrice) {
                $order['design_price'] = $designPrice;
                $eventDesc[] = '修改了设计费为'.$designPrice;
            }
            if($order['post_print_price'] != $postPrintPrice) {
                $order['post_print_price'] = $postPrintPrice;
                $eventDesc[] = '修改了印后费为'.$postPrintPrice;
            }
            if($order['install_price'] != $installPrice) {
                $order['install_price'] = $installPrice;
                $eventDesc[] = '修改了安装费为'.$installPrice;
            }
            if($order['tax_price'] != $taxPrice) {
                $order['tax_price'] = $taxPrice;
                $eventDesc[] = '修改了税费为'.$taxPrice;
            }
            if($order['other_price'] != $otherPrice) {
                $order['other_price'] = $otherPrice;
                $eventDesc[] = '修改了其它费用为'.$otherPrice;
            }
            if($order['total_price'] != $totalPrice) {
                $order['total_price'] = $totalPrice;
                $eventDesc[] = '修改了总费用为'.$totalPrice;
            }

            if($order['discount_price'] != $discountPrice) {
                $order['discount_price'] = $discountPrice;
                $eventDesc[] = '修改了优惠金额为'.$discountPrice;
            }
            if($order['real_price'] != $realPrice) {
                $order['real_price'] = $realPrice;
                $eventDesc[] = '修改了实际金额为'.$realPrice;
            }
            if($order['remark'] != $remark) {
                $order['remark'] = $remark;
                $eventDesc[] = '修改了备注为'.$remark;
            }

            $order['update_time'] = date('Y-m-d H:i:s');
            $ok = (bool) $order->save();
            if(!$ok) { throw new RunException('修改失败(1)'); }

            foreach($business as $b) {
                $bFind = $order->details()->where('bid', $b['businessId'])->first();
                if(!empty($bFind)) {
                    $consumable = (array) $b['consumable'];
                    $postPrint  = (array) $b['postPrint'];
                    $unit  = $b['unit'];
                    $content  = $b['content'];
                    $width  = $b['width'];
                    $height  = $b['height'];
                    $number  = $b['number'];
                    $price  = $b['price'];
                    $outsourceId  = $b['outsourceId'];
                    $completeDate  = $b['completeDate'];
                    $checkImg  = $b['checkImg'];
                    $insertData = [];
                    $_ct = [];
                    foreach($consumable as $v) {
                        $find = Tables\Consumable::find($v['id']);
                        if(!empty($find)) {
                            $insertData[] = [
                                'oid' => $order['id'],
                                'od_id' => $bFind['id'],
                                'bid' => $bFind['bid'],
                                'cid' => $find['id'],
                                'c_name' => $find['name'],
                                'add_time' => $addTime
                            ];
                            $_ct[]=$find['name'];
                        }
                    }
                    if(!empty($insertData)) {
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的耗材有'.implode('|', $_ct);
                        Tables\OrderConsumable::where(['od_id' => $bFind['id'], 'bid' => $bFind['bid']])->delete();
                        $ok = (bool) Tables\OrderConsumable::insert($insertData);
                        if(!$ok) {
                            throw new RunException('修改失败(2)');
                        }
                    }

                    $insertData = [];
                    $_pt = [];
                    foreach($postPrint as $v) {
                        $find = Tables\PostPrint::find($v['id']);
                        if(!empty($find)) {
                            $insertData[] = [
                                'oid' => $order['id'],
                                'od_id' => $bFind['id'],
                                'bid' => $bFind['bid'],
                                'pid' => $find['id'],
                                'p_name' => $find['name'],
                                'add_time' => $addTime
                            ];
                            $_pt[]=$find['name'];
                        }
                    }
                    if(!empty($insertData)) {
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的印后工艺有'.implode('|', $_pt);
                        Tables\OrderPostPrint::where(['od_id' => $bFind['id'], 'bid' => $bFind['bid']])->delete();
                        $ok = (bool) Tables\OrderPostPrint::insert($insertData);
                        if(!$ok) {
                            throw new RunException('修改失败(3)');
                        }
                    }

                    if($bFind['unit'] != $unit) {
                        $bFind['unit'] = $unit;
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的单位为'.$unit;
                    }
                    if($bFind['content'] != $content) {
                        $bFind['content'] = $content;
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的内容为'.$content;
                    }
                    if($bFind['width'] != $width) {
                        $bFind['width'] = $width;
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的宽为'.$width;
                    }
                    if($bFind['height'] != $height) {
                        $bFind['height'] = $height;
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的高为'.$height;
                    }
                    if($bFind['number'] != $number) {
                        $bFind['number'] = $number;
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的数量为'.$number;
                    }
                    if($bFind['price'] != $price) {
                        $bFind['price'] = $price;
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的单价为'.$price;
                    }
                    if($bFind['outsource_id'] != $outsourceId) {
                        $find = Tables\Outsource::find($outsourceId);
                        if(!empty($find)) {
                            $bFind['outsource_id'] = $find['id'];
                            $bFind['outsource_name'] = $find['name'];
                            $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的外协为'.$find['name'];
                        }
                    }
                    if($bFind['complete_date'] != $completeDate) {
                        $bFind['complete_date'] = date('Y-m-d',strtotime($completeDate));
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的完成日期为'.$completeDate;
                    }
                    if($bFind['check_img'] != $checkImg) {
                        $imgUrl = '';
                        if(!empty($checkImg)) {
                            $client = new Client();
                            $imgUrl = $client->upBase64Img($checkImg);
                            if(empty($imgUrl))  {
                                throw new RunException('图片上传失败');
                            }
                        }
                        $bFind['check_img'] = $imgUrl;
                        $eventDesc[] = '修改了订单明细'.$bFind['b_name'].'的核对图为'.$imgUrl;
                    }
                    $bFind['update_time'] = date('Y-m-d H:i:s');
                    $bFind['total_price'] = Tables\OrderDetail::getTotalPrice(
                        $bFind['count_type'], $bFind['price'],
                        $bFind['width'], $bFind['height'], $bFind['number']
                    );
                    $ok = (bool) $bFind->save();
                    if(!$ok) { throw new RunException('修改失败(4)');}
                }
            }
            $insertData = [];
            foreach($eventDesc as $v) {
                $insertData[] = [
                    'type' => Tables\OrderEvent::TYPE_Change,
                    'desc' => $v,
                    'oid'  => $order['id'],
                    'add_time' => $addTime
                ];
            }
            if(!empty($insertData)) {
                $ok = (bool) Tables\OrderEvent::insert($insertData);
                if(!$ok) {
                    throw new RunException('修改失败(5)');
                }
            }
            \DB::commit();
        }catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }


    public function getOutsourceBillList()
    {
        $id = (int) $this->request->get('id', 0);
        if($id <= 0) { return $this->responseSuccess(); }
        $list = Tables\OrderDetail::where('outsource_id', $id)
            ->where('outsource_paid', Tables\OrderDetail::Outsource_Paid_No)
            ->get();

        $r=[];
        foreach ($list as $d)  {
            $postPrint = $consumable = [];

            foreach($d->consumables as $cc) {
                $consumable[] = $cc['c_name'];
            }
            foreach($d->postPrints as $pp) {
                $postPrint[] = $pp['p_name'];
            }

            $r[] = [
                'id' => $d['id'],
                'addTime' => date('Y-m-d',$d['add_time']),
                'orderNo' => $d['oid'],
                'content' => $d['content'],
                'customerName' => $d->order()->value('customer_name'),
                'businessName' => $d['b_name'],
                'unit' => $d['unit'],
                'width' => $d['width'],
                'height' => $d['height'],
                'number' => $d['number'],
                'consumable' => $consumable,
                'postPrint' => $postPrint
            ];
        }

        return $this->responseSuccess($r);
    }

    public function FastSK() // 散客快速开单
    {
        $bid = (int) $this->request->post('bid');
        $consumable = (array) $this->request->post('consumable', []);
        $postPrint = (array) $this->request->post('postPrint', []);
        $width = (int) $this->request->post('width');
        $height = (int) $this->request->post('height');
        $number = (int) $this->request->post('number');
        $price = (int) $this->request->post('price');
        $totalPrice = (int) $this->request->post('totalPrice');
        $realPrice = (int) $this->request->post('realPrice');
        $aid = (int) $this->request->post('aid');

        if($bid <= 0) { return $this->responseFail('无信息');}
        if($number <= 0) { return $this->responseFail('数量不能为0');}
        if($price <= 0) { return $this->responseFail('单价不能为0');}
        if($aid <= 0) { return $this->responseFail('请选择收款账户');}
        if($totalPrice <= 0) { return $this->responseFail('总价不能为0');}
        if($realPrice <= 0) { return $this->responseFail('实际收款不能为0');}
        $business = Tables\Business::find($bid);
        if(empty($business)) {
            return $this->responseFail('未找到业务信息');
        }
        if($business['count_type'] != Tables\Business::COUNT_TYPE_3) {
            if($width <= 0 or $height <=0 ) {
                return $this->responseFail('请填写规格');
            }
        }

        \DB::beginTransaction();
        try{
            $addTime = time();
            $orderNo = Tables\OrderMake::make();
            if($orderNo <= 0) { throw new RunException('增加失败(1)');}
            $ok = (bool) Tables\Order::insert([
                'id' => $orderNo,
                'customer_name' => '散客',
                'total_price' => $totalPrice,
                'real_price' => $realPrice,
                'paid_price' => $realPrice,
                'make_status' => Tables\Order::Make_Status_Ok,
                'delivery_status' => Tables\Order::Delivery_Status_Ok,
                'pay_status'  => Tables\Order::Pay_status_Ok,
                'add_time'   => $addTime,
                'delivery_date' => date('Y-m-d')
            ]);
            if(!$ok) { throw new RunException('增加失败(2)');}
            $odId =  Tables\OrderDetail::insertGetId([
                'oid' => $orderNo,
                'bid' => $business['id'],
                'b_name' => $business['name'],
                'count_type' => $business['count_type'],
                'unit'  => $business['unit'],
                'width' => $width,
                'height' => $height,
                'number' => $number,
                'price'  => $price,
                'total_price' => $totalPrice,
                'make_status' => Tables\Order::Make_Status_Ok,
                'complete_date' => date('Y-m-d'),
                'add_time' => $addTime
            ]);
            if($odId <= 0) { throw new RunException('增加失败(3)');}
            if(!empty($consumable)) {
                foreach($consumable as $ccId) {
                    $c = Tables\Consumable::find($ccId);
                    if(!empty($c)) {
                        $ok = (bool) Tables\OrderConsumable::insert([
                            'oid' => $orderNo,
                            'od_id' => $odId,
                            'bid' => $business['id'],
                            'cid' => $c['id'],
                            'c_name' => $c['name'],
                            'add_time' => $addTime
                        ]);
                        if(!$ok) { throw new RunException('增加失败(3.5)');}
                    }
                }
            }
            if(!empty($postPrint)) {
                foreach($postPrint as $ppId) {
                    $p = Tables\PostPrint::find($ppId);
                    if(!empty($p)) {
                        $ok = (bool) Tables\OrderPostPrint::insert([
                            'oid' => $orderNo,
                            'od_id' => $odId,
                            'bid' => $business['id'],
                            'pid' => $p['id'],
                            'p_name' => $p['name'],
                            'add_time' => $addTime
                        ]);
                        if(!$ok) { throw new RunException('增加失败(3.55)');}
                    }
                }
            }
            $ok = (bool) Tables\CashFlow::insert([
                'change' => $realPrice,
                'desc'   => '散客快速下单 No.'.$orderNo,
                'type'   => Tables\CashFlow::TYPE_Income_Order,
                'add_time' => $addTime
            ]);
            if(!$ok) { throw new RunException('增加失败(4)');}
            $ok = (bool) Tables\OrderEvent::insert([
                'type' => Tables\OrderEvent::TYPE_Normal,
                'desc' => '散客快速开单完成',
                'oid'  => $orderNo,
                'add_time' => $addTime
            ]);
            if(!$ok) { throw new RunException('增加失败(5)');}
            $account = Tables\Account::find($aid);
            if(empty($account)) {throw new RunException('无效的收款账户');}
            $ok = (bool) Tables\OrderPay::insert([
                'oid' => $orderNo,
                'aid' => $account['id'],
                'a_name' => $account['name'],
                'money' => $realPrice,
                'add_time' => $addTime
            ]);
            if(!$ok) { throw new RunException('增加失败(6)');}
            \DB::commit();
        } catch (RunException $e) {
            \DB::rollBack();
            return $this->responseFail($e->getMessage());
        } catch (\Exception $e) {
            \DB::rollBack();
            \Log::error($e->getMessage());
            return $this->responseFail('数据库错误');
        }
        return $this->responseSuccess();
    }

    public function customerGet()
    {
        $hash = $this->request->get('hash');
        if(empty($hash)) { abort(404); }
        $find = Tables\CustomerHash::query()->where('hash', $hash)->first();
        if(empty($find)) { abort(404); }
        if($find['exp'] < time()) {
            if(empty($find)) { abort(404); }
        }
        $w = date('w');
        $w = $w == 0 ? 7 : $w;
        $w1Time = strtotime(date('Y-m-d 00:00:00'));
        for($i= 1; $i < $w ; $i++) {
            $w1Time -= 86400;
        }
        $this->request->merge([
            'cid' => $find['cid'],
            'firstDate' => date('Y-m-d', $w1Time),
            'lastDate'  => date('Y-m-d')
        ]);
        return $this->getList();
    }

}